The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284.
We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.
You are given that a2 = 512 and a10 = 614656.
Find a30.
In [1]:
512.to_s.split("").map{|i|i.to_i}.inject(:+)**(512.to_s.length)
Out[1]:
In [58]:
def check_dps(num)
base = num.to_s.split("").map{|k|k.to_i}.inject(:+)
(2..99).each do |i|
target = base ** i
return true if num == target
return false if num < target
end
return false
end
check_dps(512)
Out[58]:
In [59]:
check_dps 614656
Out[59]:
In [60]:
result = []
(11..614656).lazy.each do |num|
result << num if check_dps(num)
end
puts result
In [62]:
def find_target
result = []
(2..99).each{|k| result = result + (2..10).map{|i|k**i}}
result
end
find_target.length
Out[62]:
In [69]:
result = []
find_target.uniq.sort.each do |num|
result << num if check_dps(num)
end
puts result.sort
In [68]:
result[29]
Out[68]:
In [ ]: